//
// An echo service that receive messages from client and send back exactly the same one
//

package main

import (
	"net"
	"fmt"
	"os"
	//"time"
)

func listen(listener net.Listener, c chan string) {
	c <- fmt.Sprintf("listener goroutine in %v", os.Getpid())
	// listen for incoming connection
	conn, err := listener.Accept()
	if err != nil {
		fmt.Println(err.Error())
	}
	fmt.Printf("connected localAddr=%v remoteAddr=%v\n", conn.LocalAddr(), conn.RemoteAddr())
	content := make([]byte, 100)
	for {
		// read request
		n, err := conn.Read(content)
		if err != nil {
			//fmt.Println("error reading request: " + err.Error())
			//err.Error()
		} else {
			fmt.Println(string(content[:n]))
			// send response - the same content
			conn.Write(content)
		}
	}
	// never goes here
	conn.Close()
}

func main() {
	fmt.Printf("Main thread in pid %v\n", os.Getpid())
	c := make(chan string)
	listener, err := net.Listen("tcp", ":2999")
	if (err != nil) {
		fmt.Println(err)
		os.Exit(1)
	}
	fmt.Println("Server started")

	// accept 10 connections at most
	for i:=0; i<10; i++  {
		go listen(listener, c)
	}

	// read from channel forever
	for {
		server_log := <-c
		fmt.Println(server_log)
	}
}
